<template>
  <div class="page-container">
    <div v-if="loading" class="d-flex justify-content-center align-items-center" style="height: 300px;">
      <div class="spinner-border text-primary" role="status">
        <span class="visually-hidden">加载中...</span>
      </div>
    </div>

    <div v-else>
      <div class="d-flex justify-content-between align-items-center mb-4">
        <div class="d-flex align-items-center">
          <button class="btn btn-outline-secondary me-3" @click="goBack">
            <i class="bi bi-arrow-left me-1"></i> 返回项目
          </button>
          <h2 class="mb-0">{{ milestoneData.name }}</h2>
          <span class="badge ms-3" :class="getCategoryClass(milestoneData.category)">{{ milestoneData.category }}</span>
        </div>
        <button class="btn btn-primary" @click="editMilestone">
          <i class="bi bi-pencil me-1"></i> 编辑节点
        </button>
      </div>

      <!-- 里程碑编辑模态框 -->
      <div class="modal fade" :class="{ 'show d-block': showMilestoneModal }" tabindex="-1" role="dialog" aria-labelledby="milestoneModalLabel" :aria-hidden="!showMilestoneModal">
        <div class="modal-dialog modal-dialog-centered" role="document">
          <div class="modal-content">
            <div class="modal-header">
              <h5 class="modal-title" id="milestoneModalLabel">编辑工程节点</h5>
              <button type="button" class="btn-close" @click="closeMilestoneModal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
              <form @submit.prevent="saveMilestone">
                <div class="mb-3">
                  <label for="milestoneName" class="form-label">节点名称</label>
                  <select class="form-select" id="milestoneName" v-model="editingMilestone.name" required>
                    <option v-for="option in getMilestoneNameOptions" :key="option" :value="option">{{ option }}</option>
                  </select>
                </div>
                <div class="mb-3">
                  <label for="milestoneCategory" class="form-label">节点类别</label>
                  <select class="form-select" id="milestoneCategory" v-model="editingMilestone.category" required @change="handleCategoryChange">
                    <option value="前期">前期</option>
                    <option value="发包">发包</option>
                    <option value="施工">施工</option>
                    <option value="竣工">竣工</option>
                  </select>
                </div>
                <div class="mb-3">
                  <label for="milestonePlannedDate" class="form-label">计划日期</label>
                  <input type="date" class="form-control" id="milestonePlannedDate" v-model="editingMilestone.planned_date">
                </div>
                <div class="mb-3">
                  <label for="milestoneActualDate" class="form-label">实际日期</label>
                  <input type="date" class="form-control" id="milestoneActualDate" v-model="editingMilestone.actual_date">
                </div>
                <div class="mb-3">
                  <label for="milestoneNotes" class="form-label">备注</label>
                  <textarea class="form-control" id="milestoneNotes" v-model="editingMilestone.notes" rows="3"></textarea>
                </div>
              </form>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary" @click="closeMilestoneModal">取消</button>
              <button type="button" class="btn btn-primary" @click="saveMilestone">保存</button>
            </div>
          </div>
        </div>
      </div>
      <div class="modal-backdrop fade" :class="{ 'show': showMilestoneModal }" v-if="showMilestoneModal"></div>

      <div class="card mb-4">
        <div class="card-header">
          <h5 class="card-title mb-0">节点详情</h5>
        </div>
        <div class="card-body">
          <div class="row">
            <div class="col-md-6 mb-3">
              <div class="detail-item">
                <div class="detail-label">节点状态</div>
                <div class="detail-value">
                  <span class="badge" :class="getMilestoneStatusClass(milestoneData)">
                    {{ getMilestoneStatus(milestoneData) }}
                  </span>
                </div>
              </div>
            </div>
            <div class="col-md-6 mb-3">
              <div class="detail-item">
                <div class="detail-label">所属项目</div>
                <div class="detail-value">
                  <a href="#" @click.prevent="goToProject">{{ projectData.name }}</a>
                </div>
              </div>
            </div>
            <div class="col-md-6 mb-3">
              <div class="detail-item">
                <div class="detail-label">计划日期</div>
                <div class="detail-value">{{ milestoneData.planned_date || '-' }}</div>
              </div>
            </div>
            <div class="col-md-6 mb-3">
              <div class="detail-item">
                <div class="detail-label">实际日期</div>
                <div class="detail-value">{{ milestoneData.actual_date || '-' }}</div>
              </div>
            </div>
            <div class="col-md-6 mb-3" v-if="milestoneData.actual_date && milestoneData.planned_date">
              <div class="detail-item">
                <div class="detail-label">偏差天数</div>
                <div class="detail-value" :class="getDeviationClass(milestoneData)">
                  {{ getDeviation(milestoneData) }}
                </div>
              </div>
            </div>
            <div class="col-md-6 mb-3">
              <div class="detail-item">
                <div class="detail-label">创建时间</div>
                <div class="detail-value">{{ milestoneData.created_at || '-' }}</div>
              </div>
            </div>
            <div class="col-md-6 mb-3">
              <div class="detail-item">
                <div class="detail-label">最后更新</div>
                <div class="detail-value">{{ milestoneData.updated_at || '-' }}</div>
              </div>
            </div>
            <div class="col-12 mb-3">
              <div class="detail-item">
                <div class="detail-label">备注</div>
                <div class="detail-value p-3 bg-light rounded">
                  {{ milestoneData.notes || '暂无备注信息' }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="card mb-4">
        <div class="card-header">
          <h5 class="card-title mb-0">相关文档</h5>
        </div>
        <div class="card-body">
          <div v-if="documents.length === 0" class="text-center py-4">
            <p class="text-muted mb-0">暂无相关文档</p>
            <button class="btn btn-outline-primary mt-3">
              <i class="bi bi-upload me-1"></i> 上传文档
            </button>
          </div>
          <div v-else class="row">
            <div v-for="(doc, index) in documents" :key="index" class="col-md-4 mb-3">
              <div class="card h-100">
                <div class="card-body">
                  <h6 class="card-title">{{ doc.name }}</h6>
                  <p class="card-text small text-muted">{{ doc.upload_date }}</p>
                </div>
                <div class="card-footer bg-transparent">
                  <button class="btn btn-sm btn-outline-primary me-1">
                    <i class="bi bi-download"></i> 下载
                  </button>
                  <button class="btn btn-sm btn-outline-danger">
                    <i class="bi bi-trash"></i> 删除
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="card mb-4">
        <div class="card-header">
          <h5 class="card-title mb-0">节点历史记录</h5>
        </div>
        <div class="card-body">
          <div class="timeline">
            <div v-for="(history, index) in milestoneHistory" :key="index" class="timeline-item">
              <div class="timeline-badge" :class="getHistoryBadgeClass(history.action)">
                <i class="bi" :class="getHistoryIcon(history.action)"></i>
              </div>
              <div class="timeline-content">
                <h6 class="mb-1">{{ history.action }}</h6>
                <p class="mb-1">{{ history.description }}</p>
                <small class="text-muted">{{ history.date }} - {{ history.user }}</small>
              </div>
            </div>
            <div v-if="milestoneHistory.length === 0" class="text-center py-4">
              <p class="text-muted mb-0">暂无历史记录</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'

const route = useRoute()
const router = useRouter()
const milestoneId = parseInt(route.params.id)

// 加载状态
const loading = ref(true)

// 里程碑数据
const milestoneData = ref({})
const projectData = ref({})
const documents = ref([])
const milestoneHistory = ref([])

// 编辑模态框状态
const showMilestoneModal = ref(false)
const editingMilestone = ref({})

// 预定义的里程碑节点选项
const milestoneOptions = {
  '前期': ['任务书下达', '方案设计确认', '初步设计确认', '完成施工图审查', '完成清单编制', '完成清单审核', '施工图确认'],
  '发包': ['企业邀请/招标公告发布', '企业报名时间', '开标时间', '定标时间', '中标通知书发放时间', '合同签订时间', '直接委托'],
  '施工': ['质监注册时间', '施工许可证时间', '开工令时间', '初步验收时间'],
  '竣工': ['档案验收时间', '竣工验收时间', '实体移交时间', '档案移交时间', '竣工备案时间', '结算时间', '决算时间']
}

// 根据当前选择的类别获取节点名称选项
const getMilestoneNameOptions = computed(() => {
  if (!editingMilestone.value.category) {
    return []
  }
  return milestoneOptions[editingMilestone.value.category] || []
})

// 处理类别变更
function handleCategoryChange() {
  // 如果当前名称不在新类别的选项中，重置名称
  if (editingMilestone.value.name && !getMilestoneNameOptions.value.includes(editingMilestone.value.name)) {
    editingMilestone.value.name = getMilestoneNameOptions.value[0] || ''
  }
}

// 获取里程碑详情
async function fetchMilestoneDetail() {
  try {
    loading.value = true
    const response = await window.api.database.getMilestone(milestoneId)
    
    if (response.success) {
      milestoneData.value = response.data.milestone
      projectData.value = response.data.project
      documents.value = response.data.documents || []
      milestoneHistory.value = response.data.history || []
    } else {
      console.error('获取里程碑详情失败:', response.error)
    }
  } catch (error) {
    console.error('获取里程碑详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 获取里程碑状态
function getMilestoneStatus(milestone) {
  if (!milestone.planned_date) {
    return '未设置计划'
  }
  
  if (milestone.actual_date) {
    const planned = new Date(milestone.planned_date)
    const actual = new Date(milestone.actual_date)
    
    if (actual > planned) {
      return '延期完成'
    }
    return '已完成'
  }
  
  const now = new Date()
  const planned = new Date(milestone.planned_date)
  
  if (now > planned) {
    return '已逾期'
  }
  
  return '进行中'
}

// 获取里程碑状态样式
function getMilestoneStatusClass(milestone) {
  const status = getMilestoneStatus(milestone)
  
  switch (status) {
    case '已完成':
      return 'bg-success'
    case '延期完成':
      return 'bg-warning'
    case '已逾期':
      return 'bg-danger'
    case '进行中':
      return 'bg-info'
    default:
      return 'bg-secondary'
  }
}

// 获取里程碑分类样式
function getCategoryClass(category) {
  switch (category) {
    case '前期':
      return 'bg-info'
    case '发包':
      return 'bg-primary'
    case '施工':
      return 'bg-warning'
    case '竣工':
      return 'bg-success'
    default:
      return 'bg-secondary'
  }
}

// 获取偏差天数
function getDeviation(milestone) {
  if (!milestone.planned_date || !milestone.actual_date) {
    return '-'
  }
  
  const planned = new Date(milestone.planned_date)
  const actual = new Date(milestone.actual_date)
  const diffTime = actual - planned
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays > 0) {
    return `延期 ${diffDays} 天`
  } else if (diffDays < 0) {
    return `提前 ${Math.abs(diffDays)} 天`
  } else {
    return '准时完成'
  }
}

// 获取偏差样式
function getDeviationClass(milestone) {
  if (!milestone.planned_date || !milestone.actual_date) {
    return ''
  }
  
  const planned = new Date(milestone.planned_date)
  const actual = new Date(milestone.actual_date)
  const diffTime = actual - planned
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  
  if (diffDays > 0) {
    return 'text-danger'
  } else if (diffDays < 0) {
    return 'text-success'
  } else {
    return 'text-info'
  }
}

// 获取历史记录图标
function getHistoryIcon(action) {
  switch (action) {
    case '创建节点':
      return 'bi-plus-circle'
    case '更新节点':
      return 'bi-pencil'
    case '完成节点':
      return 'bi-check-circle'
    case '删除节点':
      return 'bi-trash'
    default:
      return 'bi-clock-history'
  }
}

// 获取历史记录徽章样式
function getHistoryBadgeClass(action) {
  switch (action) {
    case '创建节点':
      return 'bg-primary'
    case '更新节点':
      return 'bg-info'
    case '完成节点':
      return 'bg-success'
    case '删除节点':
      return 'bg-danger'
    default:
      return 'bg-secondary'
  }
}

// 返回项目页面
function goBack() {
  router.back()
}

// 跳转到项目详情
function goToProject() {
  router.push(`/project-detail/${projectData.value.id}`)
}

// 编辑里程碑
function editMilestone() {
  editingMilestone.value = { ...milestoneData.value }
  showMilestoneModal.value = true
}

// 保存里程碑
async function saveMilestone() {
  try {
    const response = await window.api.database.updateMilestone(editingMilestone.value)
    
    if (response.success) {
      // 更新本地数据
      milestoneData.value = { ...editingMilestone.value }
      
      // 关闭模态框
      showMilestoneModal.value = false
      
      // 显示成功消息
      alert('里程碑更新成功')
    } else {
      console.error('更新里程碑失败:', response.error)
      alert('更新里程碑失败: ' + response.error)
    }
  } catch (error) {
    console.error('更新里程碑失败:', error)
    alert('更新里程碑失败: ' + error.message)
  }
}

// 关闭模态框
function closeMilestoneModal() {
  showMilestoneModal.value = false
  editingMilestone.value = {}
}

// 生命周期钩子
onMounted(() => {
  fetchMilestoneDetail()
})
</script>

<style scoped>
.page-container {
  padding: 20px;
}

.detail-item {
  margin-bottom: 10px;
}

.detail-label {
  font-size: 0.875rem;
  color: #6c757d;
  margin-bottom: 5px;
}

.detail-value {
  font-weight: 500;
}

.badge {
  padding: 0.5em 0.75em;
}

.bg-success {
  background-color: #28a745 !important;
}

.bg-warning {
  background-color: #ffc107 !important;
  color: #212529 !important;
}

.bg-danger {
  background-color: #dc3545 !important;
}

.bg-info {
  background-color: #17a2b8 !important;
}

.bg-primary {
  background-color: #007bff !important;
}

.bg-secondary {
  background-color: #6c757d !important;
}

.card {
  box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075);
  margin-bottom: 20px;
}

.card-header {
  background-color: rgba(0, 0, 0, 0.03);
  border-bottom: 1px solid rgba(0, 0, 0, 0.125);
  padding: 0.75rem 1.25rem;
}

.card-header h5 {
  margin-bottom: 0;
  font-weight: 600;
}

/* 模态框样式 */
.modal {
  background-color: rgba(0, 0, 0, 0.5);
}

.modal.show {
  display: block;
}

.modal-backdrop.show {
  opacity: 0.5;
}

/* 时间线样式 */
.timeline {
  position: relative;
  padding: 20px 0;
}

.timeline-item {
  position: relative;
  margin-bottom: 30px;
  padding-left: 60px;
}

.timeline-badge {
  position: absolute;
  left: 0;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  text-align: center;
  line-height: 40px;
  color: white;
}

.timeline-badge i {
  font-size: 1.2rem;
}

.timeline-content {
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 4px;
  position: relative;
}

.timeline-content:before {
  content: '';
  position: absolute;
  left: -10px;
  top: 15px;
  width: 0;
  height: 0;
  border-top: 10px solid transparent;
  border-bottom: 10px solid transparent;
  border-right: 10px solid #f8f9fa;
}
</style> 